<template>
  <el-dialog
    title="分配权限"
    :visible.sync="status"
    width="40%"
    :before-close="handleClose"
  >
    <el-tree
      v-if="status"
      :data="data"
      ref="tree"
      show-checkbox
      node-key="auth_id"
      :default-expanded-keys="defaultCheckedKeys"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
    >
    </el-tree>

    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="status = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
    <!-- 底部按钮 -->
  </el-dialog>
</template>

<script>
import { getAuthApi } from "@/api/auth";
import { putRoleAssignApi } from "@/api/role";

export default {
  props: {
    handleTableData: {
      type: Function,
      required: true,
    },
  },
  methods: {
    handleClose(done) {
      done();
    },
    async handleSubmit() {
      // 获取数据：勾一个子-仅子、子都勾-父+子
      const allChooseData = this.$refs.tree.getCheckedNodes();
      // auth_ids  父+子
      let auth_ids = [];
      // auth_ids_son 仅子
      let auth_ids_son = [];
      // 采集数据
      allChooseData.forEach((item) => {
        auth_ids.push(item.auth_id);
        if (item.auth_pid != 0) auth_ids_son.push(item.auth_id);
      });
      auth_ids = [...new Set(auth_ids)];
      auth_ids_son = [...new Set(auth_ids_son)];

      console.log("父+子：", auth_ids);
      console.log("子：", auth_ids_son);
      // this.status = false

      const res = await putRoleAssignApi({
        role_id: this.row.role_id,
        auth_ids: auth_ids.join(","),
        auth_ids_son: auth_ids_son.join(","),
      });
      if (res.meta.state == 200) {
        this.$message.success(res.meta.msg);
        this.status = false;
        this.handleTableData();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
  },
  async created() {
    const auths = await getAuthApi();
    this.data = auths.data;
  },
  watch: {
    row: {
      handler(newData) {
        this.defaultCheckedKeys = newData.auth_ids_son
          ? newData.auth_ids_son.split(",")
          : [];
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      status: false,
      row: {},
      data: [],
      defaultProps: {
        children: "children",
        label: "auth_name",
      },
      defaultCheckedKeys: [],
      // ...
    };
  },
};
</script>
